<template>
  <div class="provider-list-container">
    <!-- 查询 -->
    <el-form :inline="true" :model="searchFrom" class="demo-form-inline">
      <el-form-item label="供应商编码">
        <el-input v-model="searchFrom.proCode"></el-input>
      </el-form-item>
      <el-form-item label="供应商名称">
        <el-input v-model="searchFrom.proName"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="doSearch">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格列表 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="proCode" label="供应商编码" width="120">
      </el-table-column>
      <el-table-column prop="proName" label="供应商名称" width="180">
      </el-table-column>
      <el-table-column prop="proContact" label="供应商联系人">
      </el-table-column>
      <el-table-column prop="proPhone" label="联系电话">
      </el-table-column>
      <el-table-column prop="proFax" label="传真">
      </el-table-column>
      <el-table-column prop="creationDate" label="创建时间">
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button size="small" @click="handleShow(scope.$index, scope.row)">查看</el-button>
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <div class="pagination-block">
      <el-pagination 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[3, 5, 10]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" 
        :total="pagination.total">
      </el-pagination>
    </div>

    <!-- 查看 -->
    <el-dialog title="查看供应商信息" v-model="showFormVisible">
      <el-form :model="showForm">
        <el-form-item label="供应商编码" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.proCode"></el-input>
        </el-form-item>
        <el-form-item label="供应商名称" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.proName"></el-input>
        </el-form-item>
        <el-form-item label="供应商详细描述" :label-width="formLabelWidth">
          <el-input type="textarea" autocomplete="off" disabled v-model="showForm.proDesc"></el-input>
        </el-form-item>
        <el-form-item label="供应商联系人" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.proContact"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.proPhone"></el-input>
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth">
          <el-input type="textarea" autocomplete="off" disabled v-model="showForm.proAddress"></el-input>
        </el-form-item>
        <el-form-item label="传真" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.proFax"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.creationDate"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="showFormVisible = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑 -->
    <el-dialog title="编辑供应商信息" v-model="editFormVisible">
      <el-form :model="editForm" :rules="rules" ref="editFormRef">
        <el-form-item label="供应商编码" prop="proCode" :label-width="formLabelWidth">
          <el-input v-model="editForm.proCode" disabled></el-input>
        </el-form-item>
        <el-form-item label="供应商名称" prop="proName" :label-width="formLabelWidth">
          <el-input v-model="editForm.proName"></el-input>
        </el-form-item>
        <el-form-item label="供应商详细描述" prop="proDesc" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="editForm.proDesc"></el-input>
        </el-form-item>
        <el-form-item label="供应商联系人" prop="proContact" :label-width="formLabelWidth">
          <el-input v-model="editForm.proContact"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="proPhone" :label-width="formLabelWidth">
          <el-input v-model="editForm.proPhone"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="proAddress" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="editForm.proAddress"></el-input>
        </el-form-item>
        <el-form-item label="传真" prop="proFax" :label-width="formLabelWidth">
          <el-input v-model="editForm.proFax"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="doUpdate()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { updateProvider, deleteProvider } from '@/api/provider'

export default {
  name: 'ProviderList',
  setup() {
    // 查询表单
    const searchFrom = reactive({
      proCode: "",
      proName: ""
    })

    // 表格数据
    const tableData = ref([])

    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 3,
      total: 0
    })

    // 查看对话框
    const showFormVisible = ref(false)
    const showForm = reactive({
      proCode: '',
      proName: '',
      proDesc: '',
      proContact: '',
      proPhone: '',
      proAddress: '',
      proFax: '',
      creationDate: ''
    })
    
    // 编辑对话框
    const editFormVisible = ref(false)
    const editForm = reactive({
      id: '',
      proCode: '',
      proName: '',
      proDesc: '',
      proContact: '',
      proPhone: '',
      proAddress: '',
      proFax: ''
    })
    const editFormRef = ref(null)
    
    const rules = reactive({
      proName: [
        { required: true, message: '请输入供应商名称', trigger: 'blur' }
      ],
      proContact: [
        { required: true, message: '请输入供应商联系人', trigger: 'blur' }
      ],
      proPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' }
      ]
    })
    
    const formLabelWidth = '120px'

    // 方法
    function doSearch() {
      // 每次点击查询时需要从第一页开始查询,将当前页码设置为第一页
      pagination.currentPage = 1
      // 调用查询方法doList
      doList()
    }

    function handleShow(index, row) {
      showFormVisible.value = true
      console.log(index, row)
      
      // 将row对象中的数据取出显示在页面中
      showForm.proCode = row.proCode
      showForm.proName = row.proName
      showForm.proDesc = row.proDesc
      showForm.proContact = row.proContact
      showForm.proPhone = row.proPhone
      showForm.proAddress = row.proAddress
      showForm.proFax = row.proFax
      showForm.creationDate = row.creationDate
    }
    
    function handleEdit(index, row) {
      editFormVisible.value = true
      console.log(index, row)
      
      // 将row对象中的数据取出显示在页面中
      editForm.id = row.id
      editForm.proCode = row.proCode
      editForm.proName = row.proName
      editForm.proDesc = row.proDesc
      editForm.proContact = row.proContact
      editForm.proPhone = row.proPhone
      editForm.proAddress = row.proAddress
      editForm.proFax = row.proFax
    }
    
    function doUpdate() {
      // 直接使用editFormRef，不再需要formName参数
      if (!editFormRef.value) {
        console.error('表单引用不存在');
        return;
      }
      
      editFormRef.value.validate((valid) => {
        if (valid) {
          updateProvider(editForm).then(resp => {
            // 获取后端返回的实际数据
            const responseData = resp.data;
            console.log("更新供应商响应:", responseData);
            
            if (responseData.flag === true) {
              // 提示成功消息
              ElMessage({
                message: responseData.message || '更新成功',
                type: 'success'
              })
              // 关闭对话框
              editFormVisible.value = false
              // 重新请求列表数据
              doList()
            } else {
              ElMessage.error(responseData.message || '更新失败')
            }
          }).catch(err => {
            console.error("更新供应商出错:", err)
            ElMessage.error('网络请求失败')
          })
        }
      })
    }
    
    function handleDelete(index, row) {
      ElMessageBox.confirm('此操作将永久删除该供应商, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProvider(row.id).then(resp => {
          // 获取后端返回的实际数据
          const responseData = resp.data;
          console.log("删除供应商响应:", responseData);
          
          if (responseData.flag === true) {
            // 提示成功消息
            ElMessage({
              message: responseData.message || '删除成功',
              type: 'success'
            })
            // 重新请求最新列表数据
            pagination.currentPage = 1
            doList()
          } else {
            ElMessage.error(responseData.message || '删除失败')
          }
        }).catch(err => {
          console.error("删除供应商出错:", err)
          ElMessage.error('网络请求失败')
        })
      }).catch(() => {
        // 取消操作
      })
    }

    function handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      // 更新每页大小
      pagination.pageSize = val
      // 发送请求
      doList()
    }

    function handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      // 更新当前页码
      pagination.currentPage = val
      // 发送请求
      doList()
    }

    function doList() {
      request({
        url: '/provider/list',
        method: 'get',
        params: {
          currentPage: pagination.currentPage,
          pageSize: pagination.pageSize,
          proCode: searchFrom.proCode,
          proName: searchFrom.proName
        }
      }).then(resp => {
        console.log("API完整响应:", resp)
        // 由于修改了拦截器，现在需要访问 resp.data 获取后端返回的实际数据
        const responseData = resp.data;
        console.log("后端返回数据:", responseData)
        
        // 处理服务端响应的结果
        if (responseData.flag === true) {
          tableData.value = responseData.data.list
          console.log("获取的供应商列表:", tableData.value)
          // 赋值分页
          pagination.currentPage = responseData.data.currentPage
          pagination.pageSize = responseData.data.pageSize
          pagination.total = responseData.data.totalCount
        } else {
          ElMessage.error(responseData.message || '获取供应商列表失败')
        }
      }).catch(err => {
        console.error("获取供应商列表出错:", err)
        ElMessage.error('网络请求失败')
      })
    }

    // 页面加载时调用函数
    onMounted(() => {
      doList()
    })

    return {
      searchFrom,
      tableData,
      pagination,
      showFormVisible,
      showForm,
      editFormVisible,
      editForm,
      rules,
      editFormRef,
      formLabelWidth,
      doSearch,
      handleShow,
      handleEdit,
      handleDelete,
      doUpdate,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.provider-list-container {
  padding: 20px;
}

.pagination-block {
  margin-top: 20px;
  text-align: right;
}
</style>